let api_ajax = function (method, url, data, dataType, suc, err) {
  data = data || null
  dataType = dataType || 'json'
  suc = suc || null
  err = err || null
  $.ajax({
    type: method,
    url: api_host + url,
    data: data,
    dataType: dataType,
    xhrFields: {
      withCredentials: true
    },
    success: function (response) {
      if (typeof response === 'string') {
        response = $.parseJSON(response)
      }
      if (response.code == 0) {
        if (typeof suc === 'function') {
          suc(response.data)
        }
      }else {
        console.log('code:' + response.code + ' msg:' + response.msg)
        layer.msg(response.msg)
        err(response.data)
      }
    },
    error: function () {}
  })
}

;(function ($, global) { // 请求图形验证码
  let $captcha = $('.captcha-img')
  $captcha.click(function () {
    _ajax()
  })

  let _ajax = function () {api_ajax('GET', 'api/tool/captcha', {}, 'json', suc)}

  let suc = function (data) {
    $captcha.attr('src', data.captcha_src)
  }
}(jQuery, window))

;(function ($, global) { // 发送邮件验证码
  let $form = $('#register-email-form')
  if ($form.length == 0) {
    return
  }
  let $sumbit = $form.find('button.submit')
  let $ico = $sumbit.find('span.fa')
  let old_class = $ico[0].className
  let $btn_p = $sumbit.find('p')
  let old_p = $btn_p.html()
  let req = null
  let msg = ''

  let verify = {
    email: {
      required: true,
      pattern: /^[_a-zA-Z0-9\-\.]+@([\-_a-zA-Z0-9]+\.)+[a-zA-Z0-9]{2,3}$/,
      errMsg: '邮箱格式不正确'
    },
    captcha: {
      required: true,
      errMsg: '验证码不能为空'
    }
  }
  console.log(verify)

  $sumbit.click(function () {
    req = initReq()
    if (!paramVerify(req)) {
      layer.msg(msg)
      return
    }
    console.log(req)

    spin()
    disBtn()
    _ajax()
  })

  let _ajax = function () {api_ajax('GET', 'api/tool/emailCaptcha', req, 'json', suc, err)}

  let suc = function (data) {
    layer.msg('邮件发送成功,请注意查收')
    stopSpin()
    let limit = 60
    let interval = setInterval(function () {
      if (limit === 0) {
        $btn_p.html(old_p)
        actBtn()
        clearInterval(interval)
      }else {
        $btn_p.html('&nbsp;&nbsp;' + limit + '秒后重新发送')
        limit--
      }
    }, 1000)
  }
  let err = function () {
    actBtn()
    stopSpin()
  }
  let spin = function () {
    $ico.removeClass().addClass('fa fa-fw fa-spinner fa-pulse')
  }
  let stopSpin = function () {
    $ico.removeClass().addClass(old_class)
  }
  let disBtn = function () {
    $sumbit.attr('disabled', 'disabled')
  }
  let actBtn = function () {
    $sumbit.removeAttr('disabled')
  }

  let initReq = function () {
    let req = {
      _token: $form.find('input[name=_token]').val(),
      code_type: $form.find('input[name=code_type]').val(),
      email: $form.find('input[name=email]').val(),
      captcha: $form.find('input[name=captcha]').val()
    }
    return req
  }

  let paramVerify = function (req) {
    for (field in verify) {
      if (!req.hasOwnProperty(field)) {
        msg = verify.field.errMsg
        return false
      } else {
        let val = req[field]
        let param = verify[field]
        if (param.hasOwnProperty('required') && param.required === true) {
          if (val == '') {
            msg = param.errMsg
            return false
          }
        }
        if (param.hasOwnProperty('pattern')) {
          pattern = param.pattern
          if (!pattern.test(val)) {
            msg = param.errMsg
            return false
          }
        }
      }
    }
    return true
  }
}(jQuery, window))

;(function ($, global) { // 注册
  let $form = $("#doregister-form")
  let $submit = $form.find("button.submit")

  let verify = {
    email: {
      required: true,
      pattern: /^[_a-zA-Z0-9\-\.]+@([\-_a-zA-Z0-9]+\.)+[a-zA-Z0-9]{2,3}$/,
      errMsg: '邮箱格式不正确'
    },
    name: {
      required: true,
      errMsg: '昵称不能为空'
    },
    password: {
      required: true,
      errMsg: '密码不符合规范'
    },
    repassword: {
      required: true,
      errMsg: '重复密码不一致'
    },
    captcha: {
      required: true,
      errMsg: '验证码不能为空'
    }
  }

  let fnInitReq = function () {
    let req = {
      _token: $form.find('input[name=_token]').val(),
      code: $form.find('input[name=code]').val(),
      name: $form.find('input[name=name]').val(),
      email: $form.find('input[name=email]').val(),
      password: $form.find('input[name=password]').val(),
      repassword: $form.find('input[name=repassword]').val(),
      captcha: $form.find('input[name=captcha]').val()
    }
    return req
  }

  let fnRegisterAjax = function (data) {
    fnApiAjax('POST', 'user/register', data, 'json', fnRegisterSuccess, fnRegisterError)
  }

  let fnRegisterSuccess = function(data) {
    layer.msg("注册成功")
    // localStorage.setItem('user_uid', data.uid)
    // localStorage.setItem('user_name', data.name)
  }

  let fnRegisterError = function() {}

  let fnTrigger = function () {
    $submit.click(function () {
      let req = fnInitReq()
      if (!fnReqVerify(req, verify)) {
        return
      }
      req.password = md5(req.password)
      req.repassword = md5(req.repassword)
      fnBtnDisable($(this))
      fnRegisterAjax(req)
    })
  }

  fnTrigger()
}(jQuery, window))

;(function ($, global) { // 注册
  let $form = $("#dologin-form")
  let $submit = $form.find("button.submit")
  let $captcha = $form.find("#captcha")
  let $captcha_img = $captcha.find('img.captcha-img')

  let verify = {
    name: {
      required: true,
      errMsg: '邮箱格式不正确'
    },
    password: {
      required: true,
      errMsg: '密码不符合规范'
    }
  }

  let fnInitReq = function () {
    let req = {
      _token: $form.find('input[name=_token]').val(),
      name: $form.find('input[name=name]').val(),
      password: $form.find('input[name=password]').val(),
      captcha: $form.find('input[name=captcha]').val()
    }
    return req
  }

  let fnLoginAjax = function (data) {
    fnApiAjax('POST', 'user/login', data, 'json', fnLoginSuccess, fnLoginError)
  }

  let fnLoginSuccess = function(data) {
    layer.msg("登录成功")
    localStorage.setItem('user_uid', data.uid)
    localStorage.setItem('user_name', data.name)
    if (data.redirect) {
      window.location.href = data.redirect
    }
  }

  let fnLoginError = function(data) {
    if (data.login_need_captcha == 1) {
      $captcha.show()

      if (data.captcha_src) {
        $captcha_img.attr('src', data.captcha_src)
      }
    }else {
      $captcha.hide()
    }
    console.log(data)
  }

  let fnTrigger = function () {
    $submit.click(function () {
      let req = fnInitReq()
      if (!fnReqVerify(req, verify)) {
        return
      }
      req.password = md5(req.password)
      fnBtnDisable($(this))
      fnLoginAjax(req)
    })
  }

  fnTrigger()
}(jQuery, window))